<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<uni-forms :model="form" :rules="rules" ref="refForm" labelAlign="right" label-width="90px">
			<view class="content-bgc">
				<view class="b-con">
					<uni-forms-item label="退货单号" name="code" required>
						<view style="display: flex;gap:20rpx">
							<uni-easyinput v-model="form.code" placeholder="请输入退货单号" class="iptBor" :inputBorder="false"
								:disabled="switchCode" />
							<view style="margin-left: 20rpx" v-show="pageInfo.type == 'add'">
								<u-switch v-model="switchCode" @change="switchChange" size="20" />
								自动生成
							</view>
						</view>
					</uni-forms-item>
					<uni-forms-item label="销售单号" name="market_order" required>
						<uni-data-select mode="underline" placeholder="请选择销售单" v-model="form.market_order" :localdata="order_list"
							:clear="true" :disabled="pageInfo.type == 'edit'" @change="order_change" />
					</uni-forms-item>
					<uni-forms-item label="交货日期" v-show="form.market_order != null">
						<uni-easyinput v-model="mar_or.delivery_date" class="iptBor" :inputBorder="false" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="客户" v-show="form.market_order != null">
						<uni-easyinput v-model="mar_or.client_name" class="iptBor" :inputBorder="false" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="数量" v-show="form.market_order != null">
						<uni-easyinput v-model="mar_or.num" class="iptBor" :inputBorder="false" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="已出货数量" v-show="form.market_order != null">
						<uni-easyinput v-model="mar_or.up_num" class="iptBor" :inputBorder="false" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="已退货数量" v-show="form.market_order != null">
						<uni-easyinput v-model="mar_or.up_sales_num" class="iptBor" :inputBorder="false" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="订单金额" v-show="form.market_order != null">
						<uni-easyinput v-model="mar_or.total_price" class="iptBor" :inputBorder="false" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="退货日期" name="sales_date" required>
						<view class="dateTimeBottom">
							<uni-datetime-picker type="datetime" placeholder="请选择退货日期" :clear-icon="false" v-model="form.sales_date"
								@show="car_popup_Show = false" @maskClick="car_popup_Show = true" @change="car_popup_Show = true"
								:border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="备注：" name="desc">
						<uni-easyinput type="textarea" v-model="form.desc" placeholder="请输入备注" />
					</uni-forms-item>
				</view>
			</view>
			<view class="car-jiesuan" @click="car_popupShow = !car_popupShow" v-show="car_popup_Show">
				<view class="fotter-icon">
					<image class="cartIcon" src="@/static/adjust_icon_01.png"></image>
				</view>
				<view class="fotter-texts">
					<u--text type="info" :text="`产品数量：${form.product_list.length}`"></u--text>
				</view>
				<view class="fotter-btn" :class="{ btnBgc: Boolean(form.product_list.length) }" v-show="car_popupShow"
					@click.stop="save">提交</view>
				<view style="margin-left: auto;" v-show="!car_popupShow"><u--text text="点击查看" type="primary" suffixIcon="eye"
						iconStyle="font-size: 40rpx;color:#3c9cff" /></view>
			</view>

			<custom-popup :popupShow="car_popupShow" mode="bottom" title="产品" class="car-popup-custom"
				@close="car_popupShow = false" height="70vh">
				<z-paging v-if="car_popupShow" ref="paging_car" :refresher-enabled="false" :loading-more-enabled="false" :fixed="false"
					v-model="form.product_list" @query="queryList_car">
					<template #top>
						<view class="zpagin_top">
							<view class="search">
								<view class="hint-text">退货数应在 0 和 (已发货数 - 已退货数量) 之间</view>
							</view>
						</view>
					</template>
					<uni-card v-for="(item, index) in form.product_list" :title="item.name" :sub-title="item.code" :key="index"
						margin="5px" spacing="0">

						<view class="ctent">规格：{{ item.specification }}</view>
						<view class="con">
							<view class="ctent ">成本价：{{ item.cost }}</view>
							<view class="ctent ">销售单价：{{ item.main_price }}</view>
						</view>
						<view class="con">
							<view class="ctent ">订单数量：{{ item.num }}</view>
							<view class="ctent ">优惠率（%）：{{ item.discount }}</view>
						</view>
						<view class="con">
							<view class="ctent ">总金额：{{ item.total_price }}</view>
							<view class="ctent ">已出货：{{ item.up_num }}</view>
						</view>
						<view class="ctent ">已退货：{{ item.slaes_num }}</view>
						<uni-forms-item label="退回仓库：" :name="`product_list[${index}].warehouse_id`" required
							:rules="[{ required: true, errorMessage: `请选择【${item.name}】的发货仓库` }]">
							<uni-data-select mode="underline" placeholder="请选择发货仓库" v-model="item.warehouse_id"
								:localdata="getWarList(item.warehouse_list)" :clear="false" placement="top" />
						</uni-forms-item>
						<view class="con">
							<view class="ctent date_text" style="flex: none;">退货数：</view>
							<custom-num-box v-model="item.now_num" :min="0" @change="change_num($event, item)" :asyncChange="true"
								:decimal-length="2"></custom-num-box>
						</view>
						<view class="con">
							<view class="ctent ">退货总金额：{{ item.now_price }}</view>
							<view class="ctent ">单位：{{ item.sales_unit }}</view>
						</view>
					</uni-card>
					<template #bottom>
						<view class="zhanwei"></view>
					</template>
				</z-paging>
			</custom-popup>
		</uni-forms>
	</view>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import oSalesInApi from '../../../api/order/o_sales_in'
import { generateCode } from '@/utils/index.js';
import Decimal from 'decimal.js-light';

//页面标题
const pageInfo = reactive({
	navbarTitle: '销售单退货',
	type: '',
	edit_id: null,
});
onLoad(option => {
	get_order_list()
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = pageInfo.navbarTitle + '(修改)'
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = pageInfo.navbarTitle + '(新增)'
		form.code = generateCode('RO')
	}
})
//自动生成按钮
const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode('RO')
	}
};
const refForm = ref(null);
const form = reactive({
	code: '',
	market_order: null,
	sales_date: '',
	desc: '',
	product_list: []
});
const fields = Object.keys(form);
const rules = {
	code: { rules: [{ required: true, errorMessage: '请输入退货单号' }] },
	market_order: { rules: [{ required: true, type: 'number', errorMessage: '请选择销售单号' }] },
	sales_date: { rules: [{ required: true, errorMessage: '请选择发货日期' }] },
}

const mar_or = reactive({
	delivery_date: '',
	client_name: '',
	num: 0,
	up_num: 0,
	up_sales_num: 0,
	total_price: 0,
});

function get_detail(id) {
	oSalesInApi.sales_order_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields)
		Object.assign(form, record)
		oSalesInApi.market_order_detail(res.market_order).then(res2 => {
			mar_or.delivery_date = res2.delivery_date
			mar_or.client_name = res2.client_name
			res2.market_order_products.forEach(v => {
				const total_price = parseFloat(v.total_price)
				mar_or.num = mar_or.num + parseFloat(v.num)
				mar_or.up_num = mar_or.up_num + parseFloat(v.finish_num)
				mar_or.up_sales_num = mar_or.up_sales_num + parseFloat(v.slaes_num)
				mar_or.total_price = mar_or.total_price + total_price
			})

			form.product_list = res.sales_order_products.map(v => {
				const stock_list = v.product.stock_info
				const warehouse_list = stock_list.map(k => ({
					id: k.warehouse_id,
					inventory: k.inventory,
					info: k.warehouse_name + '【' + k.unit_info + '】'
				}))
				return {
					id: v.product.id,
					code: v.product.code,
					name: v.product.name,
					specification: v.product.specification,
					cost: v.cost,
					main_price: v.main_price,
					num: v.num,
					discount: parseFloat(v.discount),
					now_price: v.now_price,
					total_price: v.total_price,
					up_num: v.up_num,
					slaes_num: v.up_sales_num,
					warehouse_list: warehouse_list,
					warehouse_id: v.warehouse,
					sales_unit: v.sales_unit,
					now_num: v.now_num,
					inventory: v.product.inventory
				}
			})
		})
	})
}

function order_change(v) {
	mar_or.num = 0
	mar_or.up_num = 0
	mar_or.up_sales_num = 0
	mar_or.total_price = 0
	form.product_list = []
	if (!v) {
		form.market_order = null
		return
	}
	oSalesInApi.market_order_detail(v).then(res => {
		mar_or.delivery_date = res.delivery_date
		mar_or.client_name = res.client_name
		form.product_list = res.market_order_products.map(v => {
			const total_price = parseFloat(v.total_price)
			const stock_list = v.product.stock_info
			const warehouse_list = stock_list.map(k => ({
				id: k.warehouse_id,
				inventory: k.inventory,
				info: k.warehouse_name + '【' + k.unit_info + '】'
			}))
			mar_or.num = mar_or.num + parseFloat(v.num)
			mar_or.up_num = mar_or.up_num + parseFloat(v.finish_num)
			mar_or.up_sales_num = mar_or.up_sales_num + parseFloat(v.slaes_num)
			mar_or.total_price = mar_or.total_price + total_price

			return {
				id: v.product.id,
				code: v.product.code,
				name: v.product.name,
				specification: v.product.specification,
				cost: v.cost,
				main_price: v.main_price,
				num: v.num,
				discount: parseFloat(v.discount),
				total_price: v.total_price,
				up_num: v.finish_num,
				now_num: 0,
				slaes_num: v.slaes_num,
				warehouse_list: warehouse_list,
				sales_unit: v.market_unit,
				inventory: v.product.inventory
			}
		})
	})
}

function getWarList(list) {
	return list.map(v => ({
		text: v.info, value: v.id, inventory: v.inventory
	}))
};
const car_popup_Show = ref(true);
const car_popupShow = ref(false);
const paging_car = ref(null);
function queryList_car() {
	paging_car.value.complete(form.product_list);
}

function change_num(e, row) {
	if (!row.warehouse_id) {
		return uni.$u.toast('请选择仓库')
	}
	if (e.value > row.up_num - row.slaes_num) {
		row.now_num = row.up_num - row.slaes_num
		return uni.$u.toast('退货数应在 0 和 (已发货数 - 已退货数量) 之间')
	}
	row.now_num = e.value
	const all = new Decimal(row.main_price).mul(new Decimal(row.now_num || 0))
	const discount = new Decimal(row.discount || 0)
	const now_price = all.sub(all.mul(discount).div(100))
	row.now_price = now_price.toDecimalPlaces(2).toNumber()
}

const order_list = ref([])
function get_order_list() {
	const params = { page: 1, page_size: 99999, status: 2 }
	oSalesInApi.get_market_order(params).then(res => {
		order_list.value = res.results.map(v => ({
			text: v.code,
			value: v.id
		}))
	})
}

//提交操作
function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		if (pageInfo.type == 'add') {
			oSalesInApi.post_sales_order(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			oSalesInApi.patch_sales_order(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}

	}).catch((error) => {
		console.log(error)
		uni.$u.toast(error[0].errorMessage);
	})
}

function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('o_sales_in:refresh')
		}
	})
}
</script>

<style lang="scss" scoped></style>